/**
 * 
 */
package wong.board.client.widgets;

import java.util.ArrayList;

import wong.board.client.widgets.Button.ButtonCallback;

import com.google.gwt.event.dom.client.DomEvent;

/**
 * @author wong
 * 
 */
public class ButtonsContainer<V> extends Container implements HasButtons<V> {

	private ArrayList<ButtonCallback<V>> callbacks;
	private UIHandler handler;
	private ArrayList<Button<V>> buttons;

	/**
	 * 
	 */
	public ButtonsContainer() {
		this.setStyleName(widgetsCss.buttonsContainer());
	}

	@Override
	public void addCallback(ButtonCallback<V> callback) {
		if (callbacks == null) {
			callbacks = new ArrayList<ButtonCallback<V>>();
		}
		callbacks.add(callback);
	}

	@Override
	public void removeCallback(ButtonCallback<V> callback) {
		if (callbacks == null) {
			return;
		}
		callbacks.remove(callback);
	}

	protected void callAction(Button<V> button, DomEvent<?> event) {
		if (callbacks == null) {
			return;
		}
		for (ButtonCallback<V> callback : callbacks) {
			callback.onAction(button, event);
		}
	}

	@Override
	public void addButton(Button<V> button) {
		if (handler == null) {
			handler = new UIHandler();
		}
		button.addCallback(handler);
		getContainer().add(button);
		if (buttons == null) {
			buttons = new ArrayList<Button<V>>();
		}
		buttons.add(button);
	}

	@Override
	public void removeButton(Button<V> button) {
		if (buttons != null) {
			buttons.remove(button);
		}
		if (handler != null) {
			button.removeCallback(handler);
		}
		getContainer().remove(button);
	}

	@Override
	public void clear() {
		if (handler != null) {
			for (Button<V> button : buttons) {
				button.removeCallback(handler);
			}
			handler = null;
		}
		if (buttons != null) {
			buttons.clear();
			buttons = null;
		}
		getContainer().clear();
	}

	/* 
	 * 
	 */

	private class UIHandler implements ButtonCallback<V> {

		@Override
		public void onAction(Button<V> button, DomEvent<?> event) {
			callAction(button, event);
		}
	}

}
